package com.wooophone.webapp.admin.web.action;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.wooophone.common.util.JsonSfUtil;
import com.wooophone.common.util.YamlUtil;
import com.wooophone.common.web.action.BaseAction;
import com.wooophone.mpyeah.biz.BrandBiz;
import com.wooophone.mpyeah.biz.BrandCategoryBiz;
import com.wooophone.mpyeah.biz.OnLineStoreBiz;
import com.wooophone.mpyeah.biz.RealStoreBiz;
import com.wooophone.mpyeah.entity.Brand;
import com.wooophone.mpyeah.entity.BrandCategory;
import com.wooophone.mpyeah.entity.OnLineStore;
import com.wooophone.mpyeah.entity.RealStore;

public class BrandAction extends BaseAction {
	private static final Logger log = Logger.getLogger(BrandAction.class);
	private static final long serialVersionUID = 1L;

	private Brand brand;
	private BrandBiz brandBiz;
	private OnLineStoreBiz onLineStoreBiz;
	private RealStoreBiz realStoreBiz;
	private BrandCategoryBiz brandCategoryBiz;
	private List<Brand> brandList;
	private String cid;
	private BrandCategory brandCategory;
	private String keyword;
	private String[] brandIdList;
	private String categoryIds;
	private String categoryNames;
	private int level;
	private String[] gradeFields;
	private String gradeFieldStr;

	private String filePath;

	@SuppressWarnings("unchecked")
	public String list() {
		try {
			if (cid == null || "".equals(cid)) {
				pager.setRecordCount(brandBiz.count());
				brandList = brandBiz.list(
						(pager.getCurrPageNo() - 1) * pager.getPageSize(),
						pager.getPageSize());
			} else {
				Map<String, Object> brandMap = new HashMap<String, Object>();
				brandMap = brandBiz.findBrandsAndChildBrandByCid(cid,
						(pager.getCurrPageNo() - 1) * pager.getPageSize(),
						pager.getPageSize());
				brandList = (List<Brand>) brandMap.get("brands");
				int count = (Integer) brandMap.get("count");
				pager.setRecordCount(count);
			}
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}

	}

	
	public String save() {
		try {

			Brand brandOld = brandBiz.findByName(brand.getName());
			if (null != brandOld) {
				return error(getText("brand.save.exitsError"));
			}
			List<String> list=getParameterGradeFields();
			brand.setGradeFields(JsonSfUtil.toJsonByJsonLib(list));
			brand.setLogo(filePath);
			brand.setStatus(1);
			brand.setCid(categoryIds);
			brand.setAvailable(true);
			brand.setCreator(ServletActionContext.getRequest()
					.getUserPrincipal().getName());
			String[] categoryId = categoryIds.split(",");
			Set<BrandCategory> set = new HashSet<BrandCategory>();
			for (String str : categoryId) {
				BrandCategory brandCategory = new BrandCategory();
				brandCategory.setId(str);
				set.add(brandCategory);
			}
			brand.setCategorySet(set);
			try {
				brandBiz.save(brand);
			} catch (Exception e) {
				e.printStackTrace();
				return error(getText("brand.save.exception"));
			}
			Map<String, Object> result = new HashMap<String, Object>();
			if (brand != null && brand.getId() != null) {
				if (AJAX.equals(type)) {
					result.put("status", "success");
					return ajax(result);
				} else {
					this.sendUrl = "brand_list.action?cid=" + cid; // =已更改====================categoryids
					return success(getText("brand.save.success"));

				}
			} else {
				if (AJAX.equals(type)) {
					result.put("status", "error");
					result.put("message", getText("brand.save.error"));
					return ajax(result);
				} else {
					return error(getText("brand.save.error"));
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return SUCCESS;
	}

	@RequiredStringValidator(fieldName = "id", key = "noid", message = "no id")
	public String delete() {
		boolean flag = this.isValidateStoreByBrandId(id);
		if (flag) {
			return ajax("[{'status':'error','message':'"
					+ getText("brand.validata.existStore") + "'}]");
		}
		int r = 0;
		try {
			r = brandBiz.delete(id);
		} catch (Exception e) { // CannotDeleteException
			e.printStackTrace();

			return ajax("[{'status':'error','message':'"
					+ getText("brand.validata.existStore") + "'}]");
		}

		if (r > 0) {
			return ajax("[{'status':'success','message':'"
					+ getText("brand.delete.success") + "'}]");
		} else {
			return ajax("[{'status':'error','message':'"
					+ getText("brand.delete.error") + "'}]");
		}

	}

	public String update() {
		Brand brandOld = null;
		String[] categoryId = categoryIds.split(",");
		Set<BrandCategory> set = new HashSet<BrandCategory>();
		for (String str : categoryId) {
			BrandCategory brandCategory = new BrandCategory();
			brandCategory.setId(str);
			set.add(brandCategory);
		}
		List<String> list=getParameterGradeFields();
		
		if (brand != null && brand.getId() != null && !"".equals(brand.getId())) {
			brandOld = brandBiz.get(brand.getId());
			brandOld.setCredit(brand.getCredit());
			brandOld.setDescription(brand.getDescription());
			brandOld.setJudge(brand.getJudge());
			brandOld.setMore(brand.getMore());
			brandOld.setName(brand.getName());
			brandOld.setScore(brand.getScore());
			brandOld.setTomlive(brand.getTomlive());
			brandOld.setGradeFields(JsonSfUtil.toJsonByJsonLib(list));
			brandOld.setCategorySet(set);
		}
		if (cid != null && !"".equals(cid)) {
			brandOld.setCid(cid);
		}
		if (filePath != null && !"".equals(filePath)) {
			brandOld.setLogo(filePath);
		}

		try {
			int r = brandBiz.update(brandOld);
			if (r > 0) {
				return success(getText("brand.update.success"));
			} else {
				return error(getText("brand.update.error"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_PAGE;
		}

	}

	@RequiredStringValidator(fieldName = "id", key = "noid", message = "no id")
	public String view() {
		brand = brandBiz.get(id);
		return SUCCESS;
	}

	public String input() {
		try {
			if (cid != null) {
				brandCategory = brandCategoryBiz.get(cid);
				this.categoryNames = brandCategory.getName();
				this.categoryIds = brandCategory.getId();
				
				
				List<Object> list = brandCategoryBiz
						.findRecommendGradeFields(cid);
				this.setParameterGradeFields(list);
			}
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String listGradeFields() {
		String[] fields = null;
		
		if (categoryIds != null) {
			fields = categoryIds.split(",");
			List<Object> list = brandCategoryBiz
					.findRecommendGradeFields(fields);
			int length=list.size();
			gradeFields=new String[length];
			for (int i = 0; i < length; i++) {
				gradeFields[i] = list.get(i).toString();
			}
		}
		
		YamlUtil.serializationOutputToConsole(gradeFields);
		
		if(gradeFields!=null){
			return ajax(gradeFields);
		}else{
			return ajax(new String[0]);
		}
	}

	@RequiredStringValidator(fieldName = "id", key = "noid", message = "no id")
	public String edit() {
		try {
			brand = brandBiz.get(id);
			brand.setGradeFields(brand.getGradeFields().replace("[", ""));
			brand.setGradeFields(brand.getGradeFields().replace("]", ""));
			brand.setGradeFields(brand.getGradeFields().replace("\"", ""));
			
			Set<BrandCategory> set = brand.getCategorySet();
			Iterator<BrandCategory> iter = set.iterator();
			categoryIds = "";
			categoryNames = "";
			while (iter.hasNext()) {
				BrandCategory brandCategory = iter.next();
				categoryIds += brandCategory.getId() + ",";
				categoryNames += brandCategory.getName() + ",";
			}
			if(categoryNames.lastIndexOf(",")>0){
				categoryNames=categoryNames.substring(0,categoryNames.lastIndexOf(","));
			}
			List<BrandCategory> brandCategoryList=brandBiz.findCategoryList(brand.getId());
			String[] cids=null;
			int brandCategoryListLength=0;
			if(brandCategoryList!=null){
				 brandCategoryListLength= brandCategoryList.size();
				cids=new String[brandCategoryListLength];
				for (int i = 0; i < brandCategoryListLength; i++) {
					cids[i]=brandCategoryList.get(i).getId();
				}
			}
			
			if(brandCategoryListLength>0){
				List<Object> list=brandCategoryBiz.findRecommendGradeFields(cids);
				this.setParameterGradeFields(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}

	public String search() {
		try {
			if (null == keyword && "".equals(keyword)) {
				return list();
			} else {
				String keywordString = keyword;
				pager.setRecordCount(brandBiz.count(keywordString));
				brandList = brandBiz.search(keywordString,
						(pager.getCurrPageNo() - 1) * pager.getPageSize(),
						pager.getPageSize());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;

	}

	public String deleteSelect() {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			for (String id : brandIdList) {
				if (this.vlidataBrandIsExistStore(id)) {
					result.put("status", "error");
					result.put("message", "所选的品牌下存在店铺,请删除店铺后再试");
					return ajax(result);
				}
			}
			int r = 0;
			for (int i = 0; i < brandIdList.length; i++) {
				r = brandBiz.delete(brandIdList[i]);
				r++;
			}
			if (r > 0) {
				if (AJAX.equals(type)) {
					result.put("status", "success");
					result.put("count", r);
					return ajax(result);
				} else {
					return SUCCESS;
				}
			}
			if (AJAX.equals(type)) {
				return ajax(Status.error);

			} else {
				result.put("status", "error");
				result.put("message", "删除失败");
				return ajax(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_PAGE;
		}

	}

	/** 验证品牌下是否存在店铺 */
	public boolean vlidataBrandIsExistStore(String brandId) {
		Map<String, Object> parameter = new HashMap<String, Object>();
		parameter.put("brandId", brandId);
		List<OnLineStore> list = onLineStoreBiz.find(parameter);
		if (list.size() > 0) {
			return true;
		} else {

			List<RealStore> realStoresList = realStoreBiz.find(parameter);
			if (realStoresList != null) {
				if (realStoresList.size() > 0) {
					return true;
				}
			}
		}
		return false;

	}

	@RequiredStringValidator(fieldName = "id", key = "noid", message = "no id")
	public String commend() {
		try {
			brand = brandBiz.get(id);
			brand.setLevel(level);
			brandBiz.update(brand);
			return ajax(Status.success);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return ajax(Status.error);
	}

	// 验证品牌下是否有店铺
	private boolean isValidateStoreByBrandId(String brandId) {
		boolean flag = false;
		// Map<String, Object> parameter=new HashMap<String, Object>();
		// parameter.put("brandId", brandId);
		flag = onLineStoreBiz.countByBrandId(brandId) > 0;
		if (!flag) {
			flag = realStoreBiz.countByBrandId(id) > 0;
		}
		return flag;

	}

	public Brand getBrand() {
		return brand;
	}

	public void setBrand(Brand brand) {
		this.brand = brand;
	}

	public void setCid(String cid) {
		this.cid = cid;
	}

	public BrandCategory getBrandCategory() {
		return brandCategory;
	}

	public void setBrandCategory(BrandCategory brandCategory) {
		this.brandCategory = brandCategory;
	}

	public List<Brand> getBrandList() {
		return brandList;
	}

	public void setBrandBiz(BrandBiz brandBiz) {
		this.brandBiz = brandBiz;
	}

	public void setBrandCategoryBiz(BrandCategoryBiz brandCategoryBiz) {
		this.brandCategoryBiz = brandCategoryBiz;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public void setBrandIdList(String[] brandIdList) {
		this.brandIdList = brandIdList;
	}

	public String getCategoryIds() {
		return categoryIds;
	}

	public void setCategoryIds(String categoryIds) {
		this.categoryIds = categoryIds;
	}

	public String getCategoryNames() {
		return categoryNames;
	}

	public void setCategoryNames(String categoryNames) {
		this.categoryNames = categoryNames;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public String getCid() {
		return cid;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setOnLineStoreBiz(OnLineStoreBiz onLineStoreBiz) {
		this.onLineStoreBiz = onLineStoreBiz;
	}

	public void setRealStoreBiz(RealStoreBiz realStoreBiz) {
		this.realStoreBiz = realStoreBiz;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String[] getGradeFields() {
		return gradeFields;
	}

	public void setGradeFields(String[] gradeFields) {
		this.gradeFields = gradeFields;
	}

	public String getGradeFieldStr() {
		return gradeFieldStr;
	}

	public void setGradeFieldStr(String gradeFieldStr) {
		this.gradeFieldStr = gradeFieldStr;
	}
	
	private List<String> getParameterGradeFields(){
		gradeFieldStr=gradeFieldStr.replace("，", ",");
		gradeFieldStr=gradeFieldStr.trim();
		String[] tempStr=gradeFieldStr.split(",");
		
		List<String> list=Arrays.asList(tempStr);
		for (int i = 0; i < list.size(); i++) {
			String str=list.get(i);
			if(str==null||"".equals(str)){
				list.remove(i);
				i--;
			}
		}
		return list;
	}
	
	private void setParameterGradeFields(List<Object> list){
		gradeFieldStr = "";
		if (list != null) {
			int length=list.size();
			gradeFields=new String[length];
			for (int i = 0; i <length ; i++) {
				String str=list.get(i).toString();
				gradeFields[i] = str;
				gradeFieldStr+=str+",";
			}
			gradeFieldStr=gradeFieldStr.substring(0,gradeFieldStr.lastIndexOf(","));
		}
	}
}